;;; guile-gcrypt --- crypto tooling for guile
;;; Copyright © 2012, 2013, 2014, 2015, 2016 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2019 Brendan Tildesley <mail@brendan.scot>
;;;
;;; This file is part of guile-gcrypt.
;;;
;;; guile-gcrypt is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; guile-gcrypt is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with guile-gcrypt.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gcrypt hash)
  #:use-module (gcrypt common)
  #:use-module (gcrypt utils)
  #:use-module (rnrs bytevectors)
  #:use-module (ice-9 binary-ports)
  #:use-module (ice-9 hash-table)
  #:use-module (system foreign)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:export (hash
            open-hash-input-port
            open-hash-port
            port-hash
            file-hash

            ;; Deprecated
            sha1
            sha256
            open-sha256-port
            port-sha256
            file-sha256
            open-sha256-input-port))

;;; Commentary:
;;;
;;; Cryptographic hashes.
;;;
;;; Code:


;;;
;;; Hash.
;;;

;; Algorithm ID's can be found in libgcrypt's src/gcrypt.h.in.


;; I tried using gcry_md_get_algo_dlen get the hash lengths, but it does not
;; work for every available algorithm, so they are embedded here.
(define get-algorithm-data
  (let ((data
         (alist->hashq-table
          (list         ;; Algorithm ID | Hash length (bytes).
           (cons 'md5            (cons 1 16))
           (cons 'sha1           (cons 2 20))
           (cons 'rmd160         (cons 3 20))
           ;; 6 is TIGER from GnuPG < 1.3.2, so we use the tiger symbol for the updated
           ;; TIGER1.
           (cons 'sha256         (cons 8 32))
           (cons 'sha384         (cons 9 48))
           (cons 'sha512         (cons 10 64))
           (cons 'sha224         (cons 11 28))
           (cons 'md4            (cons 301 16))
           (cons 'crc32          (cons 302 4))
           (cons 'crc32-rfc1510  (cons 303 4))
           (cons 'crc24-rfc2440  (cons 304 3))
           (cons 'whirlpool      (cons 305 64))
           (cons 'tiger          (cons 306 24)) ; GCRY_MD_TIGER1
           (cons 'tiger2         (cons 307 24))
           (cons 'gostr3411-94   (cons 308 32))
           (cons 'stribog256     (cons 309 32))
           (cons 'stribog512     (cons 310 64))
           (cons 'gostr3411cp    (cons 311 32))
           (cons 'sha3-224       (cons 312 28))
           (cons 'sha3-256       (cons 313 32))
           (cons 'sha3-384       (cons 314 48))
           (cons 'sha3-512       (cons 315 64))
           (cons 'blake2b-512    (cons 318 64))
           (cons 'blake2b-384    (cons 319 48))
           (cons 'blake2b-256    (cons 320 32))
           (cons 'blake2b-160    (cons 321 20))
           (cons 'blake2s-256    (cons 322 32))
           (cons 'blake2s-224    (cons 323 28))
           (cons 'blake2s-160    (cons 324 20))
           (cons 'blake2s-128    (cons 325 16))))))
    (lambda (algorithm)
      (let ((data (hashq-ref data algorithm)))
        (if data
            data
            (error (string-append
                    (symbol->string algorithm)
                    " does not appear to be a supported digest algorithm.")))))))

(define (hash-size algorithm)
  (cdr (get-algorithm-data algorithm)))

(define (algorithm-id algorithm)
  (car (get-algorithm-data algorithm)))

(define hash
  (let ((hash (pointer->procedure void
                                  (libgcrypt-func "gcry_md_hash_buffer")
                                  `(,int * * ,size_t))))
    (lambda* (bv algorithm #:optional size)
      "Return the hash HASH, using the digest ALGORITHM, of BV as a
bytevector. For variable length hashes, SIZE must be specified."
      (let* ((size (if size size (hash-size algorithm)))
             (digest (make-bytevector size)))
        (hash (algorithm-id algorithm)
              (bytevector->pointer digest)
              (bytevector->pointer bv)
              (bytevector-length bv))
        digest))))

(define (sha1 bv) (hash bv 'sha1))
(define (sha256 bv) (hash bv 'sha256))

(define open-hash-md
  (let ((open (pointer->procedure int
                                  (libgcrypt-func "gcry_md_open")
                                  `(* ,int ,unsigned-int))))
    (lambda (algorithm)
      (let* ((md  (bytevector->pointer (make-bytevector (sizeof '*))))
             (err (open md (algorithm-id algorithm) 0)))
        (if (zero? err)
            (dereference-pointer md)
            (throw 'gcrypt-error err))))))

(define md-write
  (pointer->procedure void
                      (libgcrypt-func "gcry_md_write")
                      `(* * ,size_t)))

(define md-read
  (pointer->procedure '*
                      (libgcrypt-func "gcry_md_read")
                      `(* ,int)))

(define md-close
  (pointer->procedure void
                      (libgcrypt-func "gcry_md_close")
                      '(*)))



(define (open-hash-port algorithm)
  "Return two values: an output port, and a thunk.  When the thunk is called,
it returns the hash (a bytevector) of all the data written to the
output port with the specified hash algorithm."
  (define hash-md
    (open-hash-md algorithm))

  (define digest #f)
  (define position 0)

  (define (finalize!)
    (let ((ptr (md-read hash-md 0)))
      (set! digest (bytevector-copy
                    (pointer->bytevector ptr (hash-size algorithm))))
      (md-close hash-md)))

  (define (write! bv offset len)
    (if (zero? len)
        (begin
          (finalize!)
          0)
        (let ((ptr (bytevector->pointer bv offset)))
          (md-write hash-md ptr len)
          (set! position (+ position len))
          len)))

  (define (get-position)
    position)

  (define (close)
    (unless digest
      (finalize!)))

  (values (make-custom-binary-output-port (symbol->string algorithm)
                                          write! get-position #f
                                          close)
          (lambda ()
            (unless digest
              (finalize!))
            digest)))

(define (port-hash algorithm port)
  "Return the hash (a bytevector) of all the data drained from PORT with the
specified hash algorithm."
  (let-values (((out get)
                (open-hash-port algorithm)))
    (dump-port port out)
    (close-port out)
    (get)))

(define (open-hash-input-port algorithm port)
  "Return an input port that wraps PORT and a thunk to get the hash of all the
data read from PORT.  The thunk always returns the same value."
  (define md
    (open-hash-md algorithm))

  (define (read! bv start count)
    (let ((n (get-bytevector-n! port bv start count)))
      (if (eof-object? n)
          0
          (begin
            (unless digest
              (let ((ptr (bytevector->pointer bv start)))
                (md-write md ptr n)))
            n))))

  (define digest #f)

  (define (finalize!)
    (let ((ptr (md-read md 0)))
      (set! digest (bytevector-copy
                    (pointer->bytevector ptr (hash-size algorithm))))
      (md-close md)))

  (define (get-hash)
    (unless digest
      (finalize!))
    digest)

  (define (unbuffered port)
    ;; Guile <= 2.0.9 does not support 'setvbuf' on custom binary input ports.
    ;; If you get a wrong-type-arg error here, the fix is to upgrade Guile.  :-)
    (setvbuf port _IONBF)
    port)

  (values (unbuffered (make-custom-binary-input-port (symbol->string algorithm) read! #f #f #f))
          get-hash))

(define (file-hash algorithm file)
  (call-with-input-file file (cut port-hash algorithm <>)))

(define (open-sha256-input-port port) (open-hash-input-port 'sha256 port))
(define (open-sha256-port) (open-hash-port 'sha256))
(define (port-sha256 port) (port-hash 'sha256 port))
(define (file-sha256 file) (file-hash 'sha256 file))

;;; hash.scm ends here
